from django.shortcuts import render, get_object_or_404, redirect
from blueapps.account.models import User
from .models import Teacher, Student, Role, Course, Homework, Handin
from .forms import RegistrationForm, ProfileForm, CourseForm, HomeworkForm, HandinForm, \
    CommentForm
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.urls import reverse, reverse_lazy

from django.views.generic import DetailView, ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
import json


def logout(request):
    return redirect('https://paas-class.bktencent.com/login/?c_url=https://paas-class.bktencent.com/o/bkupwork/&app_code=bkupwork')


def index(request):
    if not Role.objects.filter(user=request.user.id):
        return HttpResponseRedirect(reverse('project:register'))
    return render(request, 'project/index.html')


def register(request):
    if request.method == 'POST':
        # 验证表单RegistrationForm的数据是否有效
        form = RegistrationForm(request.POST)
        print(form)
        if form.is_valid():
            role = form.cleaned_data['role']
            user = request.user
            role_profile = Role(role=int(role), user=user)
            role_profile.save()
            # 如果直接使用objects.create()方法后不需要使用save()
            if int(role) == 0:
                user_profile = Student(user=role_profile)
                user_profile.save()
            else:
                user_profile = Teacher(user=role_profile)
                user_profile.save()
            #  注册成功，通过HttpResponseRedirect方法转到登录页面
            return HttpResponseRedirect(reverse('project:index'))
    else:
        form = RegistrationForm()
    return render(request, 'project/register.html', {'form': form})


def profile(request, pk):
    user = get_object_or_404(User, pk=pk)
    return render(request, 'project/profile.html', {'user': user})


def profile_update(request, pk):
    user = get_object_or_404(User, pk=pk)
    if request.method == "POST":
        form = ProfileForm(request.POST)
        if form.is_valid():
            if request.user.role.role == 0:
                user.role.student.name = form.cleaned_data['name']
                user.role.student.gender = form.cleaned_data['gender']
                user.role.student.description = form.cleaned_data['description']
                user.role.student.save()
                # 请重新复习一遍 URL 重定向的三种方法
                return HttpResponseRedirect(reverse('project:profile', args=[user.id]))
            else:
                user.role.teacher.name = form.cleaned_data['name']
                user.role.teacher.gender = form.cleaned_data['gender']
                user.role.teacher.description = form.cleaned_data['description']
                user.role.teacher.save()
                return HttpResponseRedirect(reverse('project:profile', args=[user.id]))
    else:
        if request.user.role.role == 0:
            default_data = {'name': user.role.student.name,
                            'gender': user.role.student.gender,
                            'description': user.role.student.description,
                            }
        else:
            default_data = {'name': user.role.teacher.name,
                            'gender': user.role.teacher.gender,
                            'description': user.role.teacher.description,
                            }
        form = ProfileForm(default_data)
    return render(request, 'project/profile_update.html', {'form': form, 'user': user})


class CourseList(ListView):
    template_name = 'project/course_list.html'

    def get_queryset(self):
        return Course.objects.all().order_by("id")


class CourseListSelf(ListView):
    template_name = 'project/course_list_self.html'

    def get_queryset(self):
        # 根据用户角色来返回相应数据
        if self.request.user.role.role == 1:
            return Course.objects.filter(teacher=self.request.user.role.teacher).order_by("id")
        else:
            return Course.objects.filter(student=self.request.user.role.student).order_by("id")


class CourseDetail(DetailView):
    model = Course
    template_name = 'project/course_detail.html'


class CourseCreate(CreateView):
    model = Course
    form_class = CourseForm
    template_name = 'project/course_form.html'

    def form_valid(self, form):
        form.instance.teacher = self.request.user.role.teacher
        return super().form_valid(form)


class CourseUpdate(UpdateView):
    model = Course
    form_class = CourseForm
    template_name = 'project/course_form.html'

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.teacher != self.request.user.role.teacher:
            raise Http404()
        return obj


class CourseDelete(DeleteView):
    model = Course
    success_url = reverse_lazy('project:course_list')

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.teacher != self.request.user.role.teacher:
            raise Http404()
        return obj


def course_select(request, pk):
    course = get_object_or_404(Course, pk=pk)
    user = get_object_or_404(User, pk=request.user.id)
    course.student.add(user.role.student)
    return HttpResponseRedirect(reverse('project:course_list_self', args=[user.id]))


def course_cancel(request, pk):
    course = get_object_or_404(Course, pk=pk)
    user = get_object_or_404(User, pk=request.user.id)
    course.student.remove(user.role.student)
    return HttpResponseRedirect(reverse('project:course_list_self', args=[user.id]))


class HomeworkListPublished(ListView):
    template_name = 'project/homework_list_published.html'
    paginate_by = 5

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.course.teacher != self.request.user.role.teacher:
            raise Http404()
        return obj

    def get_queryset(self):
        return Homework.objects.filter(course__id=self.kwargs['pk']).filter(status='p').order_by('-published')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        course = Course.objects.get(id=self.kwargs['pk'])
        context.update({
            'course': course,
        })
        return context


class HomeworkListDraft(ListView):
    paginate_by = 5
    template_name = 'project/homework_list_publishing.html'

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.course.teacher != self.request.user.role.teacher:
            raise Http404()
        return obj

    def get_queryset(self):
        return Homework.objects.filter(course__id=self.kwargs['pk']).filter(status='d').order_by('-published')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        course = Course.objects.get(id=self.kwargs['pk'])
        context.update({
            'course': course,
        })
        return context


class HomeworkDetail(DetailView):
    model = Homework
    template_name = 'project/homework_detail.html'

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        obj.viewed()
        return obj

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        course = Course.objects.get(id=self.kwargs['pkr'])
        form = CommentForm()
        comment_list = self.object.comment.filter(homework=self.object)
        context.update({
            'course': course,
            'form': form,  # 新增
            'comment_list': comment_list  # 新增
        })
        return context


class HomeworkCreate(CreateView):
    model = Homework
    form_class = HomeworkForm
    template_name = 'project/homework_form.html'

    def form_valid(self, form):
        form.instance.course = Course.objects.get(id=self.kwargs['pk'])
        return super().form_valid(form)


class HomeworkUpdate(UpdateView):
    model = Homework
    form_class = HomeworkForm
    template_name = 'project/homework_form.html'


class HomeworkDelete(DeleteView):
    model = Homework
    get = DeleteView.post

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.course.teacher != self.request.user.role.teacher:
            raise Http404()
        return obj

    def get_success_url(self):
        return reverse_lazy('project:homework_list_published', args=[str(self.kwargs['pkr'])])


def homework_publish(request, pk, pkr):
    homework = get_object_or_404(Homework, pk=pk)
    homework.publish()
    return redirect(reverse('project:homework_detail', args=[str(pkr), str(pk)]))


class HomeworkList(ListView):
    def get_queryset(self):
        return Homework.objects.filter(course__id=self.kwargs['pk']).filter(status='p').order_by('-published')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        course = Course.objects.get(id=self.kwargs['pk'])
        homework = [x for x in self.get_queryset()]
        judge = [0 for i in range(len(homework))]
        score = []
        for each in homework:
            handin = Handin.objects.filter(homework=each, author=self.request.user.role.student)
            if len(handin):
                if handin[0].score:
                    score.append(handin[0].score)
                else:
                    score.append('未打分')
            else:
                score.append('未提交')
        handin = Handin.objects.filter(course__id=self.kwargs['pk']).filter(author=self.request.user.role.student)
        for handin in handin:
            if handin.homework in homework:
                judge[homework.index(handin.homework)] = 1
        # zip 函数将两个列表合并，返回一个 tuple
        info = list(zip(homework, judge, score))
        context.update({
            'course': course,
            'judge': judge,
            'info': info,
        })
        return context


class HandinListDone(ListView):
    template_name = 'project/handin_list_done.html'
    paginate_by = 5

    def get_queryset(self):
        return Handin.objects.filter(course__id=self.kwargs['pk']).filter(
            author=self.request.user.role.student).order_by('-id')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        course = Course.objects.get(id=self.kwargs['pk'])
        context.update({
            'course': course,
        })
        return context


class HandinCreate(CreateView):
    model = Handin
    form_class = HandinForm
    template_name = 'project/handin_form.html'

    def form_valid(self, form):
        homework = Homework.objects.get(id=self.kwargs['pk'])
        course = Course.objects.get(id=self.kwargs['pkr'])
        form.instance.course = course
        form.instance.homework = homework
        form.instance.author = self.request.user.role.student
        return super().form_valid(form)


class HandinDetail(DetailView):
    model = Handin
    template_name = "project/handin_detail.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        homework = Homework.objects.get(id=self.kwargs['pkr'])
        context.update({
            'homework': homework,
        })
        return context


class HandinUpdate(UpdateView):
    model = Handin
    form_class = HandinForm
    template_name = 'project/handin_form.html'


class HandinDelete(DeleteView):
    model = Handin

    def get_success_url(self):
        return reverse_lazy('project:homework_list', args=[str(self.kwargs['pka'])])

    def get_object(self, queryset=None):
        obj = super().get_object(queryset=queryset)
        if obj.author != self.request.user.role.student:
            raise Http404()
        return obj

    def get(self, request, *args, **kwargs):
        return self.post(request, *args, **kwargs)


class HomeworkHandin(ListView):
    model = Handin
    template_name = 'project/homework_handin_count.html'

    def get_queryset(self):
        return Handin.objects.filter(course__id=self.kwargs['pkr']).filter(homework__id=self.kwargs['pk'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        homework = Homework.objects.get(id=self.kwargs['pk'])
        # 调用 models.py 中的 student_count 方法以统计学生人数
        total = Course.objects.get(id=self.kwargs['pkr']).student_count()
        # 使用 count() 方法统计属于该课程的作答作业 即已提交的作业数量
        done = Handin.objects.filter(homework=homework).count()
        context.update({
            'homework': homework,
            'total': total,
            'done': done,
        })
        return context


def course_student(request, pk):
    course = Course.objects.get(pk=pk)
    student = course.student.all()
    return render(request, 'project/course_student.html', context={'student': student, 'course': course})


def homework_comment(request, pk):
    homework = get_object_or_404(Homework, pk=pk)
    comment_list = homework.comment.filter(homework=homework)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.homework = homework
            if request.user.role.role == 1:
                comment.username = request.user.role.teacher.name
            else:
                comment.username = request.user.role.student.name
            comment.save()
            return redirect(homework)
        else:
            context = {'homework': homework,
                       'form': form,
                       'comment_list': comment_list
                       }
            return render(request, 'homework/homework_detail.html', context=context)
    return redirect(homework)


def score(request, pk):
    value = request.POST.get('value')
    handin = Handin.objects.get(pk=pk)
    handin.score = value
    handin.save()
    return HttpResponse("1")


def get_score(request):
    course = request.GET.get('course')
    username = request.GET.get('value')
    author = User.objects.get(username=username)
    handin = Handin.objects.filter(course__id=course, author=author.role.student).order_by('homework')
    print(handin)
    homework_list = []
    score_list = []
    for each in handin:
        if each.score:
            homework_list.append(each.homework.title)
            score_list.append(each.score)
    data = {'homework': homework_list, 'score': score_list}
    return HttpResponse(json.dumps(data))
